package com.leenleda.ips.util;

import android.app.ActivityManager;
import android.app.Service;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.media.AudioManager;
import android.os.Build;
import android.os.Environment;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.widget.Toast;

import com.leenleda.ips.MyApplication;
import com.leenleda.ips.receiver.Constant;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import static android.content.Context.ACTIVITY_SERVICE;

public class Utils {

//    //****************SharedPreferences******************
//    public static final boolean putString(Context context, String key, String value) {
//        value = value == null ? "" : value;
//        SharedPreferences.Editor editor = getSharedPreference(context).edit();
//        editor.putString(key, value);
//        boolean result = editor.commit();
//        if (!result) {
//            return false;
//        }
//        return true;
//    }
//
//    public static final boolean putString(String key, String value) {
//        value = value == null ? "" : value;
//        SharedPreferences.Editor editor = getSharedPreference(MyApplication.getInstance()).edit();
//        editor.putString(key, value);
//        boolean result = editor.commit();
//        if (!result) {
//            return false;
//        }
//        return true;
//    }
//
//    private static final SharedPreferences getSharedPreference(Context context) {
//        return PreferenceManager.getDefaultSharedPreferences(context);
//    }
//
//    public static final String getString(Context context, String key) {
//        return getSharedPreference(context).getString(key, "");
//    }
//
//    public static final String getString(String key) {
//        return getSharedPreference(MyApplication.getInstance()).getString(key, "");
//    }
//
//    public static final String getValue(Context context, String key) {
//        return getSharedPreference(context).getString(key, "");
//    }
//
//    public static final boolean putInt(Context context, String key,
//                                       int value) {
//        SharedPreferences.Editor editor = getSharedPreference(context).edit();
//        editor.putInt(key, value);
//        boolean result = editor.commit();
//        if (!result) {
//            return false;
//        }
//        return true;
//    }
//
//    public static final boolean putInt(String key, int value) {
//        SharedPreferences.Editor editor = getSharedPreference(MyApplication.getInstance()).edit();
//        editor.putInt(key, value);
//        boolean result = editor.commit();
//        if (!result) {
//            return false;
//        }
//        return true;
//    }
//
//    public static final long getLong(String key,
//                                     long default_data) {
//        return getSharedPreference(MyApplication.getInstance()).getLong(key, default_data);
//    }
//
//    public static final boolean putLong(String key, Long value) {
//        SharedPreferences.Editor editor = getSharedPreference(MyApplication.getInstance()).edit();
//        editor.putLong(key, value);
//        return editor.commit();
//    }
//
//    public static final int getIntValue(Context context, String key) {
//        return getSharedPreference(MyApplication.getInstance()).getInt(key, 0);
//    }
//
//    public static final int getIntValue(String key) {
//        return getSharedPreference(MyApplication.getInstance()).getInt(key, 0);
//    }
//
//    public static final Boolean getBooleanValue(Context context, String key) {
//        return getSharedPreference(MyApplication.getInstance()).getBoolean(key, false);
//    }
//
//    public static final Boolean getBooleanValue( String key) {
//        return getSharedPreference(MyApplication.getInstance()).getBoolean(key, false);
//    }
//
//    public static final Boolean getBooleanDefault(String key) {
//        return getSharedPreference(MyApplication.getInstance()).getBoolean(key, true);
//    }
//
//    public static final void putBooleanValue(String key, boolean bl) {
//        SharedPreferences.Editor edit = getSharedPreference(MyApplication.getInstance()).edit();
//        edit.putBoolean(key, bl);
//        edit.commit();
//    }
//    //****************SharedPreferences******************

    public static boolean isEmpty(String s) {
        if (null == s)
            return true;
        if (s.length() == 0)
            return true;
        if (s.trim().length() == 0)
            return true;
        return false;
    }


    public static boolean isBoolIp(String ipAddress) {
        String ip = "([1-9]|[1-9]\\d|1\\d{2}|2[0-4]\\d|25[0-5])(\\.(\\d|[1-9]\\d|1\\d{2}|2[0-4]\\d|25[0-5])){3}";
        Pattern pattern = Pattern.compile(ip);
        Matcher matcher = pattern.matcher(ipAddress);
        return matcher.matches();
    }

    private static Toast mToast;

    public static void showShortToast(String pMsg) {
        if (pMsg == null)
            return;
        if (TextUtils.isEmpty(pMsg.trim()))
            return;
        shortToast(MyApplication.getInstance(), pMsg);
    }

    private static void shortToast(Context context, String text) {
        if (mToast == null) {
            mToast = Toast.makeText(context.getApplicationContext(), text, Toast.LENGTH_LONG);
            mToast.setGravity(Gravity.CENTER, 0, 0);
        } else {
            mToast.setText(text);
            mToast.setDuration(Toast.LENGTH_LONG);
        }
        mToast.show();
    }

    //****************Toast******************

    public static final String getStringValue(String briefContent) {
        if (briefContent == null || briefContent.equalsIgnoreCase("null"))
            return "";
        return briefContent;
    }


    private static long lastClickTime;
    /*
     * 防止连续点击
     */
    public static void startActivity(Context activity, Intent intent) {
        if (intent == null)
            return;
//        long time = Utils.getSetTime();
        long time = System.currentTimeMillis();
        if (time - lastClickTime < 500) {
            return;
        }
        lastClickTime = time;
        activity.startActivity(intent);
        return;
    }

    private static long time_Double = 0;
    /*
     * 防止连续点击
     */
    public synchronized static boolean doubleClick() {//需求：toast在未消失的时候第二次点击有效（能正常推出）
        long time = System.currentTimeMillis();
        if (time - time_Double < 500) {
            return true;
        }
        time_Double = time;
        return false;
    }

    private static long aaa = 0;
    /*
     * 防止连续点击
     */
    public synchronized static boolean isFast() {//需求：toast在未消失的时候第二次点击有效（能正常推出）
        long time = System.currentTimeMillis();
        if (time - aaa < 500) {
            return true;
        }
        aaa = time;
        return false;
    }

    //    ****************清理缓存**************************
    /*
     * 清理缓存
     */
    public static void clearAllCache(Context context) {
        deleteDir(context.getCacheDir());
        if (Environment.getExternalStorageState().equals(
                Environment.MEDIA_MOUNTED)) {
            deleteDir(context.getExternalCacheDir());
        }
    }

    /**
     * 指定清楚缓存
     * @param context
     */
    public static void clearSnapCache(Context context){
        File dir = context.getCacheDir();
        LogUtils.e("SnapPicture", "-------clearSnapCache---0-----" + dir);
        if (dir != null && dir.isDirectory()) {
            String[] children = dir.list();
            LogUtils.e("SnapPicture", "-------clearSnapCache---1-----" + dir);
            for (int i = 0; i < children.length; i++) {
                LogUtils.e("SnapPicture", "-------clearSnapCache----2----" + children[i]);
                if (children[i].contains("image")) {
                    deleteDir(new File(dir, children[i]));
                }
            }
        }
    }

    public static void deleteFolder(String path){
        File file = new File(path);
        if (file == null)
            return;
        if (file.isDirectory()) {
            String[] children = file.list();
            LogUtils.e("deleteFolder", "-------deleteFolder---1-----" + file);
            if (children == null)
                return;
            for (int i = 0; i < children.length; i++) {
                LogUtils.e("deleteFolder", "-------deleteFolder----2----" + children[i]);
                deleteDir(new File(file, children[i]));
            }
            return;
        }
        file.delete();
    }

    private static boolean deleteDir(File dir) {
//        ILog.e("SnapPicture", "-------deleteDir--------" + dir);
        if (dir != null && dir.isDirectory()) {
            String[] children = dir.list();
            if (children == null)
                return true;
            for (int i = 0; i < children.length; i++) {
                boolean success = deleteDir(new File(dir, children[i]));
                if (!success) {
                    return false;
                }
            }
        }
        return dir.delete();
    }
//    ****************清理缓存**************************

    private static boolean isServiceRunning(Context context, String ServiceName) {
        if (TextUtils.isEmpty(ServiceName)) {
            return false;
        }
        ActivityManager myManager = (ActivityManager) context.getSystemService(ACTIVITY_SERVICE);
        ArrayList<ActivityManager.RunningServiceInfo> runningService = (ArrayList<ActivityManager.RunningServiceInfo>) myManager.getRunningServices(1000);
        for (int i = 0; i < runningService.size(); i++) {
//            ILog.e("SLKVNSDV", "服务运行1：" + runningService.get(i).service.getClassName().toString());
            if (runningService.get(i).service.getClassName().contains(ServiceName)) {
                return true;
            }
        }
        return false;
    }

    private static String tag = "RECEIVER";

    public static void voiceSet(Context context, int voice){
        AudioManager audioManager = (AudioManager) context.getSystemService(Service.AUDIO_SERVICE);
        LogUtils.e(tag, "====设置音量=3==" + voice );
        int max = audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
        int num = (int) (voice * 1.0 / 100 * max);
        LogUtils.e(tag, "====设置音量=4=" + max + "===num==" + num);
//        Utils.putInt(Constant.VOLUME_VALUE, num);

//        MyApplication.getInfo(20).setVolume(num);
//
//        audioManager.adjustStreamVolume(AudioManager.STREAM_MUSIC, AudioManager.ADJUST_RAISE,AudioManager.FX_FOCUS_NAVIGATION_UP);
//        audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, num, AudioManager.FLAG_PLAY_SOUND);
    }

    public static void voiceChange(Context context, int state){
        AudioManager audioManager = (AudioManager) context.getSystemService(Service.AUDIO_SERVICE);
        int max = audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
        int current = audioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
        LogUtils.e(tag, "====max=3==" + max );
        LogUtils.e(tag, "====current=3==" + current );
        LogUtils.e(tag, "====state=3==" + state );

        int num = current;
        switch (state){
            case 0://-
                num --;
                break;
            default://+
                num ++;
                break;
        }
        if (num < 0 || num > max)
            return;
        LogUtils.e(tag, "------num----" + num );

        audioManager.adjustStreamVolume(AudioManager.STREAM_MUSIC, AudioManager.ADJUST_RAISE,AudioManager.FX_FOCUS_NAVIGATION_UP);
        audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, num, AudioManager.FLAG_PLAY_SOUND);
    }

    /**
     * @return 判断是否在前台运行
     */
    public static boolean isOnForeground(Context context, String ... name){
        ActivityManager activityManager = (ActivityManager) context.getSystemService(ACTIVITY_SERVICE);
        List<ActivityManager.RunningAppProcessInfo> appProcessInfoList = activityManager.getRunningAppProcesses();
        if(appProcessInfoList == null){
            return false;
        }

        String packageName = Constant.APP_PACKAGE_NAME;
//        String packageName = MyApplication.getInfo(21).getPackageName();
        if (name.length > 0)
            packageName = name[0];
//        ILog.e("SVNSDV", "====packageName=====" + packageName);

        for(ActivityManager.RunningAppProcessInfo processInfo : appProcessInfoList){
            if(processInfo.processName.equals(packageName) && processInfo.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND ){
                return true;
            }
        }
        return false;
    }
//
//    /**
//     * @return 获取文件路径
//     */
//    public static String getPath(long folderName) {
//
//        long folderBefore = UShared.getLong(Constant.SAVE_FOLDER_NAME, 0);
//        String path = Environment.getExternalStorageDirectory() + "/mediaCache/" + folderName + "/";
//        String pathBefore = Environment.getExternalStorageDirectory() + "/mediaCache/" + folderBefore + "/";
//
//        File fileBefore = new File(pathBefore);
//        if (fileBefore != null && fileBefore.isDirectory()) {
//            fileBefore.renameTo(new File(path));
//            return path;
//        }
//
//        File file = new File(path);
//        if (file.mkdirs()) {
//            return path;
//        }
//        return path;
//    }

    public static int dip2px(Context context, float dipValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dipValue * scale + 0.5f);
    }

    public static long getSetTime(){
//        return getLong( Constant.CURRENT_SYSTEM_TIME, 0);//获取服务器设置时间
        return System.currentTimeMillis();
    }

    public static String getName(String url, int id){
        String path = "";
        String[] strs = url.split("/");
        try {
            path = url.replace(strs[strs.length - 1], "") + URLEncoder.encode(strs[strs.length - 1], "utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        String[] aa = path.split("\\.");
        if (aa.length < 2)
            return "";
        String name = id + "." + aa[aa.length - 1];
        LogUtils.e(tag, "======getName=====" + name);
        return name;
    }


    public static String getIPAddress(Context context) {
        try {
            NetworkInterface networkInterface;
            InetAddress inetAddress;
            for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements(); ) {
                networkInterface = en.nextElement();
                for (Enumeration<InetAddress> enumIpAddr = networkInterface.getInetAddresses(); enumIpAddr.hasMoreElements(); ) {
                    inetAddress = enumIpAddr.nextElement();
                    if (!inetAddress.isLoopbackAddress() && !inetAddress.isLinkLocalAddress() && inetAddress instanceof Inet4Address) {
                        String ip = inetAddress.getHostAddress();
                        LogUtils.e(tag, "=====getIPAddress===2===" + isBoolIp(ip) +  ",ip=" + ip);
                        return ip;
                    }
                }
            }
            return "";
        } catch (SocketException ex) {
            ex.printStackTrace();
            Log.e("====getIpAddress===", ex.toString());
            return "";
        }
    }


    private static long keyTime = 0;
    private static String strTag = "";
    /*
     * 防止连续点击
     */
    public synchronized static boolean dKey(String tag) {//需求：toast在未消失的时候第二次点击有效（能正常推出）

        LogUtils.e(tag, "==onKeyDown====tag=" + tag + ",strTag=" + strTag);
        if (!strTag.equalsIgnoreCase(tag)) {
            keyTime = 0;
        }
        strTag = tag;
        long time = System.currentTimeMillis();
        LogUtils.e(tag, "==onKeyDown====time=" + time );
        LogUtils.e(tag, "==onKeyDown==eyTime=" + keyTime );
        if (time - keyTime < 500) {
            return true;
        }
        keyTime = time;
        return false;
    }
}
